<?php

namespace App\Http\Middleware;

use Auth, Closure, Redirect, Route;
use Symfony\Component\HttpKernel\Exception\HttpException;

class CheckPermissions
{
    public function handle($request, Closure $next, $guard = null)
    {
        $staff = Auth::guard($guard)->user();

        if($staff->supervisor())
            return $next($request);

        //获取请求路径
        $path = $request->path();
        $controller = cutstr($path, '/', 0);
        $action = cutstr($path, '/', 1);

        //请求路径为空
        if(empty($controller) || empty($action))
            return $next($request);

        //根据请求路径生成权限名称
        $permission = $controller.'-'.$action;
        //dd($permission);
        $lists = \App\Models\Acl\Permission::all(['name'])->toArray();
        
        //如果权限不包含在权限表中，则直接跳过(路由过滤)
        if( !collect($lists)->flatten()->contains($permission) )
            return $next($request);

        //权限判断
        if ($staff->can($permission)) {
            return $next($request);
        }
        
        return abort('403');        
    }
}
